/**
 * 
 */

package io.zhijian.app.authorization;

import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;

import io.zhijian.system.entity.User;


/**
 * <p>
 * Title: PasswordHelper
 * </p>
 * <p>
 * Description:
 * </p>
 * <p>
 * Company:
 * </p>
 * 
 * @author H2013788
 */
public class PasswordHelper {

    /**
     * md5加密
     */
    private String algorithmName = "md5";
    /**
     * hashIterations
     */
    private final int hashIterations = 2;

    /**
     * 密碼加密
     * 
     * @param user 用户对象
     * @author H2013788
     * @date 2017/11/22下午7:41:53
     */
    public void encryptPassword(User user) {
        // User对象包含最基本的字段Username和Password
        // salt默認123...
        // user.setSalt(randomNumberGenerator.nextBytes().toHex());
        // 将用户的注册密码经过散列算法替换成一个不可逆的新密码保存进数据，散列过程使用了盐
        // 此加密方式為shiro自身支持的，與UserReaml中SimpleAuthenticationInfo對應
        String newPassword = new SimpleHash(algorithmName, user.getPassword(),
                ByteSource.Util.bytes(user.getCredentialsSalt()), hashIterations).toHex();
        user.setPassword(newPassword);
    }
    
    public static String getEncryptPassword(String username, String salt, String password){
        String newPassword = new SimpleHash("md5", password,
                ByteSource.Util.bytes(username + salt), 2).toHex();
        return newPassword;
    }
}
